package com.wzb.mybatisplus.bitaction.electrumaction.five;

import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;

import java.security.SecureRandom;

public class Fixed5PrivateKeyGenerator {

    private static final NetworkParameters params = MainNetParams.get();
    private static final SecureRandom secureRandom = new SecureRandom();

    public static void main(String[] args) {
        System.out.println("生成以5开头的比特币私钥 - 修复版");
        System.out.println("=========================================\n");

        generate5PrivateKey();
    }

    public static void generate5PrivateKey() {
        int attempts = 0;
        ECKey foundKey = null;

        while (true) {
            attempts++;
            ECKey key = new ECKey(secureRandom);
            String privateKeyWIF = key.getPrivateKeyAsWiF(params);

            if (privateKeyWIF.startsWith("5")) {
                foundKey = key;
                break;
            }

            if (attempts % 1000 == 0) {
                System.out.println("已尝试 " + attempts + " 次...");
            }
        }

        printKeyInfo(foundKey, attempts);
    }

    private static void printKeyInfo(ECKey key, int attempts) {
        String privateKeyWIF = key.getPrivateKeyAsWiF(params);
        String privateKeyHex = key.getPrivateKeyAsHex();

        // 修复地址生成 - 方法1: 使用 LegacyAddress
        Address address = LegacyAddress.fromKey(params, key);

        // 或者方法2: 根据脚本类型生成地址
        // Address address = key.toAddress(params, Script.ScriptType.P2PKH);

        System.out.println("尝试次数: " + attempts);
        System.out.println("私钥 (WIF): " + privateKeyWIF);
        System.out.println("私钥 (HEX): " + privateKeyHex);
        System.out.println("公钥地址: " + address.toString());
        System.out.println("是否压缩: " + key.isCompressed());

        // 验证格式
        System.out.println("✓ 格式验证: 主网未压缩私钥 (5开头)");

        // 验证私钥有效性
        validatePrivateKey(privateKeyWIF);
    }

    private static void validatePrivateKey(String privateKeyWIF) {
        try {
            DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, privateKeyWIF);
            ECKey key = dumpedPrivateKey.getKey();
            String recreatedWIF = key.getPrivateKeyAsWiF(params);

            if (privateKeyWIF.equals(recreatedWIF)) {
                System.out.println("密钥验证: ✓ 有效");
            } else {
                System.out.println("密钥验证: ✗ 无效");
            }
        } catch (Exception e) {
            System.out.println("密钥验证: ✗ 验证失败");
        }
    }
}
